//
//  MineTableViewController.m
//  TravelFollowYourHeart
//
//  Created by appleLJ on 2017/12/8.
//  Copyright © 2017年 Lwx. All rights reserved.
//

#import "MineViewController.h"
#import "MineTableTableViewCell.h"
#import "EditMyInfoTableViewController.h"
#import "MyJourneyViewController.h"
#import "MyTravelViewController.h"
#import "MyNewsViewController.h"
#import "PredetermineViewController.h"
#import "MyCollectionViewController.h"
#import "MyTakeFilmViewController.h"
#import "LoginViewController.h"
#import "ServiceCenterViewController.h"

@interface MineViewController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate>

@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) UIView *headerView;//头试图
@property(nonatomic,strong) UIView *footerView;//尾试图
@property(nonatomic,strong) NSMutableArray *dataArray;//数据源
@property(nonatomic,strong) UILabel *nickNameLabel;//用户昵称
@property(nonatomic,strong) UILabel *phoneNumberLabel;//电话号
@property(nonatomic,strong) UILabel * scoreLabel;//积分
@property(nonatomic,strong) UIImageView * headImgView;//头像
@property(nonatomic,strong) UIButton * loginBtn;
@property(nonatomic,strong) UIButton * logoutBtn;
@end

@implementation MineViewController (Networking)

- (void)getMemberInforData{

    NSDictionary *dic = @{
                          @"mid":[UserModel intance].member_id,
                          @"token":[UserModel intance].token
                          };
//    [[HUDHelper sharedInstance]syncLoading:@"登录中..."];
    [self showprogressHUD];
    [[HttpRequest shardWebUtil] postNetworkRequestURLString:Url(@"/member/member") andParas:dic andTransferGottenData:^(id obj, NSError *error) {
        [self hiddenProgressHUD];
        [[HUDHelper sharedInstance]syncStopLoading];
        if (error)
        {
            [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
        }
        else
        {
            if ([obj[@"code"] integerValue] == 100000)
            {
//                UserModel *model = [UserModel yy_modelWithDictionary:obj[@"data"]];
                self.nickNameLabel.text = obj[@"data"][@"nickname"];
                self.phoneNumberLabel.text = obj[@"data"][@"phone"];
                [self.headImgView sd_setImageWithURL:[NSURL URLWithString:obj[@"data"][@"avatar"]] placeholderImage:[UIImage imageNamed:@"list_detail_commend"]];
                int sexInt = [obj[@"data"][@"sex"] intValue];
                [UserModel intance].sex = [NSNumber numberWithInt:sexInt];
                [UserModel intance].nickname = obj[@"data"][@"nickname"];
                [UserModel intance].avatar = obj[@"data"][@"avatar"];
                [UserModel saveLogin];
            }
            else
            {
                [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
            }
        }
    }];
}

- (void)ifHaveLogin{
    if ([UserModel isSaveLogin]) {
        
    }else{
        [AppHelper showLogin];
    }
}

@end

@implementation MineViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.delegate = self;
    if ([UserModel isSaveLogin]) {
        self.loginBtn.hidden = YES;
        self.logoutBtn.hidden = NO;
//        self.nickNameLabel.text = [UserModel intance].nickname;
//        self.phoneNumberLabel.text = [UserModel intance].phone;
//        [self.headImgView sd_setImageWithURL:[NSURL URLWithString:[UserModel intance].avatar]];
        [self getMemberInforData];
    }else{
        self.loginBtn.hidden = NO;
        self.logoutBtn.hidden = YES;
        self.nickNameLabel.text = nil;
        self.phoneNumberLabel.text = nil;
        //                self.headImgView.image = [UIImage imageNamed:obj[@"data"][@"avatar"]];
        self.headImgView.image = [UIImage imageNamed:@"user_photo"];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = getColor(whiteColor);
    self.navigationItem.title = @"";
    [self.view addSubview:self.tableView];
    self.navigationController.delegate = self;
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    BOOL isHomePage = [viewController isKindOfClass:[self class]];
    [self.navigationController setNavigationBarHidden:isHomePage animated:YES];
}

#pragma mark -- event

//登录
- (void)loginBtnClick{
    LoginViewController * loginVC = [[LoginViewController alloc] init];
    [self.navigationController pushViewController:loginVC animated:YES];
}
//退出登录
- (void)logoutBtnClick{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"你确定退出登录？" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    WS(ws)
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [UserModel deleteLogin];
        ws.headImgView.image = [UIImage imageNamed:@"user_photo"];
        ws.nickNameLabel.text = nil;
        ws.phoneNumberLabel.text = nil;
        ws.logoutBtn.hidden = YES;
        ws.loginBtn.hidden = NO;
        [UserModel intance].token = nil;
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

//编辑资料
- (void)editMyinfo{
    if ([UserModel isSaveLogin]) {
        EditMyInfoTableViewController *vc = [[EditMyInfoTableViewController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [AppHelper showLogin];
    }    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MineTableTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MineTableTableViewCell class]) forIndexPath:indexPath];
    cell.model = self.dataArray[indexPath.row];
    if (indexPath.row != 7 && indexPath.row != 8) {
        //右箭头
        UIImageView *rightImgView = [[UIImageView alloc] init];
        rightImgView.image = [UIImage imageNamed:@"icon_in"];
        [cell.contentView addSubview:rightImgView];
        [rightImgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(5 / WIDTH_5S_SCALE);
            make.height.mas_equalTo(10 / WIDTH_5S_SCALE);
            make.right.equalTo(cell.contentView).offset(-10 / WIDTH_5S_SCALE);
            make.centerY.equalTo(cell.contentView);
        }];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44 / WIDTH_5S_SCALE;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        //我的行程
        if ([UserModel isSaveLogin]) {
            MyJourneyViewController *vc = [[MyJourneyViewController alloc] init];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            [AppHelper showLogin];
        }
        
    }else if (indexPath.row == 1){
        //我的预定
        if ([UserModel isSaveLogin]) {
            PredetermineViewController * predetermineVC = [[PredetermineViewController alloc] init];
            [self.navigationController pushViewController:predetermineVC animated:YES];
        }else{
            [AppHelper showLogin];
        }
        
    }else if (indexPath.row == 2){
        //我的消息
        if ([UserModel isSaveLogin]) {
            MyNewsViewController * myNewsVC = [[MyNewsViewController alloc] init];
            [self.navigationController pushViewController:myNewsVC animated:YES];
        }else{
            [AppHelper showLogin];
        }
        
    }else if (indexPath.row == 3){
        //我的收藏
        
        if ([UserModel isSaveLogin]) {
            MyCollectionViewController * myCollectionVC = [[MyCollectionViewController alloc] init];
            [self.navigationController pushViewController:myCollectionVC animated:YES];
        }else{
            [AppHelper showLogin];
        }
    }else if (indexPath.row == 4){
        //我的游记
        if ([UserModel isSaveLogin]) {
            MyTravelViewController * myTravelVC = [[MyTravelViewController alloc] init];
            myTravelVC.isPublish = YES;
            [self.navigationController pushViewController:myTravelVC animated:YES];
        }else{
            [AppHelper showLogin];
        }
        
    }else if (indexPath.row == 5){
        //我的美拍
        
        if ([UserModel isSaveLogin]) {
            MyTakeFilmViewController * myTakeFilmVC = [[MyTakeFilmViewController alloc] init];
            [self.navigationController pushViewController:myTakeFilmVC animated:YES];
        }else{
            [AppHelper showLogin];
        }
    }else if (indexPath.row == 6){
        //关于我们
        
    }else if (indexPath.row == 7){
        //客服中心
        NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",@"10086"];
        UIWebView * callWebview = [[UIWebView alloc] init];
        [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
        [self.view addSubview:callWebview];
    }else if (indexPath.row == 8){
        //清除缓存
        [self putBufferBtnClicked];
    }
}


#pragma mark -- init

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 49) style:UITableViewStylePlain];
        _tableView.backgroundColor = getColor(whiteColor);
        _tableView.separatorInset = UIEdgeInsetsZero;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableHeaderView = self.headerView;
        _tableView.tableFooterView = self.footerView;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        [_tableView registerClass:[MineTableTableViewCell class] forCellReuseIdentifier:NSStringFromClass([MineTableTableViewCell class])];
    }
    return _tableView;
}

- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 190 / WIDTH_5S_SCALE)];
        //背景图
        UIImageView *bgImgView = [[UIImageView alloc] init];
        bgImgView.image = [UIImage imageNamed:@"img_userbg"];
        //头像
        self.headImgView = [[UIImageView alloc] init];
//        self.headImgView.image = [UIImage imageNamed:@"user_photo"];
//        [self.headImgView sd_setImageWithURL:[NSURL URLWithString:AvatarUrl([UserModel intance].avatar]) placeholderImage:[UIImage imageNamed:@"list_detail_commend"]];
        self.headImgView.userInteractionEnabled = YES;
        UITapGestureRecognizer *bgImgViewTag = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(editMyinfo)];
        [self.headImgView addGestureRecognizer:bgImgViewTag];
        //昵称
        self.nickNameLabel = [[UILabel alloc] init];
        [self.nickNameLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:16]];
        self.nickNameLabel.textColor = getColor(whiteColor);
        self.nickNameLabel.textAlignment = NSTextAlignmentCenter;
        self.nickNameLabel.text = [UserModel intance].nickname;
        self.nickNameLabel.userInteractionEnabled = YES;
        UITapGestureRecognizer *nickNameLabelTag = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(editMyinfo)];
        [self.nickNameLabel addGestureRecognizer:nickNameLabelTag];
        //电话号码
        self.phoneNumberLabel = [[UILabel alloc] init];
        [self.phoneNumberLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:14]];
        //phoneNumberLabel.font = DEF_FontSize_14;
        self.phoneNumberLabel.textColor = getColor(whiteColor);
        self.phoneNumberLabel.textAlignment = NSTextAlignmentCenter;
        self.phoneNumberLabel.text = [UserModel intance].phone;
        self.phoneNumberLabel.userInteractionEnabled = YES;
        UITapGestureRecognizer *phoneNumberLabelTag = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(editMyinfo)];
        [self.phoneNumberLabel addGestureRecognizer:phoneNumberLabelTag];
        //积分
        self.scoreLabel = [[UILabel alloc] init];
        [self.scoreLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:13]];
        //scoreLabel.font = DEF_FontSize_12;
        self.scoreLabel.textColor = getColor(whiteColor);
        self.scoreLabel.textAlignment = NSTextAlignmentCenter;
//        self.scoreLabel.text = @"25000积分";
        
        //添加控件
        [_headerView addSubview:bgImgView];
        [_headerView addSubview:self.headImgView];
        [_headerView addSubview:self.nickNameLabel];
        [_headerView addSubview:self.phoneNumberLabel];
        [_headerView addSubview:self.scoreLabel];
        
        //约束
        [bgImgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.bottom.right.equalTo(_headerView);
        }];
        [self.headImgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_headerView).offset(40 / WIDTH_5S_SCALE);
            make.centerX.equalTo(_headerView);
            make.width.height.mas_equalTo(60 / WIDTH_5S_SCALE);
            self.headImgView.layer.cornerRadius = 60 / 2 / WIDTH_5S_SCALE;
            self.headImgView.layer.masksToBounds = YES;
        }];
        [self.nickNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.headImgView.mas_bottom).offset(8 / WIDTH_5S_SCALE);
            make.centerX.equalTo(_headerView);
            make.height.mas_equalTo(16 / WIDTH_5S_SCALE);
        }];
        [self.phoneNumberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.nickNameLabel.mas_bottom).offset(6 / WIDTH_5S_SCALE);
            make.centerX.equalTo(_headerView);
            make.height.mas_equalTo(14 / WIDTH_5S_SCALE);
        }];
        [self.scoreLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.phoneNumberLabel.mas_bottom).offset(8 / WIDTH_5S_SCALE);
            make.centerX.equalTo(_headerView);
            make.height.mas_equalTo(12 / WIDTH_5S_SCALE);
        }];
        
        int btnW = 70;
        self.logoutBtn = [[UIButton alloc]initWithFrame: CGRectMake(SCREEN_WIDTH -btnW - 20, 30, btnW, 25)];
        self.logoutBtn.titleLabel.font = DEF_FontSize_14;
        [self.logoutBtn setTitle:@"退出登录" forState:UIControlStateNormal];
        [self.logoutBtn addTarget:self action:@selector(logoutBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [self.headerView addSubview:self.logoutBtn];
        
//        self.loginBtn = [[UIButton alloc]initWithFrame: CGRectMake(SCREEN_WIDTH -70, 30, 60, 25)];
        self.loginBtn = [[UIButton alloc] init];
        self.loginBtn.frame = self.logoutBtn.frame;
        self.loginBtn.titleLabel.font = DEF_FontSize_14;
        [self.loginBtn setTitle:@"登录/注册" forState:UIControlStateNormal];
        [self.loginBtn addTarget:self action:@selector(loginBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [self.headerView addSubview:self.loginBtn];

        
        if ([UserModel isSaveLogin]) {
            self.loginBtn.hidden = NO;
            self.logoutBtn.hidden = YES;
        }else{
            self.loginBtn.hidden = YES;
            self.logoutBtn.hidden = NO;
        }
    }
    return _headerView;
}

- (UIView *)footerView{
    if (!_footerView) {
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40 / WIDTH_5S_SCALE)];
    }
    return _footerView;
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = @[@{@"img":@"user_xingcheng",@"title":@"我的行程"},
                       @{@"img":@"user_yuding",@"title":@"我的预定"},
                       @{@"img":@"user_xiaofei",@"title":@"我的消息"},
                       @{@"img":@"user_shoucang",@"title":@"我的收藏"},
                       @{@"img":@"user_youji",@"title":@"我的游记"},
                       @{@"img":@"user_meipai",@"title":@"我的美拍"},
                       @{@"img":@"user_women",@"title":@"关于我们"},
                       @{@"img":@"user_kefu",@"title":@"客服中心"},
                       @{@"img":@"user_qingchu",@"title":@"清除缓存"},
                       ].mutableCopy;
    }
    return _dataArray;
}

#pragma mark - 清除缓存
//清除缓存按钮的点击事件
- (void)putBufferBtnClicked{
    CGFloat size = [self folderSizeAtPath:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject] + [self folderSizeAtPath:NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject] + [self folderSizeAtPath:NSTemporaryDirectory()];
    
    NSString *message = size > 1 ? [NSString stringWithFormat:@"缓存%.0fM, 删除缓存", size] : [NSString stringWithFormat:@"缓存%.0fK, 删除缓存", size * 1024.0];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:(UIAlertControllerStyleAlert)];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
        [self cleanCaches:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject];
        [self cleanCaches:NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject];
        [self cleanCaches:NSTemporaryDirectory()];
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    [alert addAction:action];
    [alert addAction:cancel];
    [self showDetailViewController:alert sender:nil];
}

// 计算目录大小
- (CGFloat)folderSizeAtPath:(NSString *)path{
    // 利用NSFileManager实现对文件的管理
    NSFileManager *manager = [NSFileManager defaultManager];
    CGFloat size = 0;
    if ([manager fileExistsAtPath:path]) {
        // 获取该目录下的文件，计算其大小
        NSArray *childrenFile = [manager subpathsAtPath:path];
        for (NSString *fileName in childrenFile) {
            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
            size += [manager attributesOfItemAtPath:absolutePath error:nil].fileSize;
        }
        // 将大小转化为M
        return size / 1024.0 / 1024.0;
    }
    return 0;
}
// 根据路径删除文件
- (void)cleanCaches:(NSString *)path{
    // 利用NSFileManager实现对文件的管理
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        // 获取该路径下面的文件名
        NSArray *childrenFiles = [fileManager subpathsAtPath:path];
        for (NSString *fileName in childrenFiles) {
            // 拼接路径
            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
            // 将文件删除
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
    }
}

@end
